package top.zackyoung.druid.simple.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.zackyoung.druid.simple.MyDataSource;
import top.zackyoung.druid.simple.config.DynamicDataSourceSwitcher;

/**
 * 创建aop切面
 *
 * @author ZackYoung
 * @version 1.0
 * @date 2021/9/28
 */
@Aspect
@Order(1)
@Component
@Slf4j
public class DynamicDataSourceAspect {
    /**
     * 切入点只对@Service注解的类上的@DataSource方法生效
     *
     * @param myDataSource 自定义注解
     */
    @Pointcut(value = "@within(org.springframework.stereotype.Service) && @annotation(myDataSource)")
    public void dynamicDataSourcePointCut(MyDataSource myDataSource) {
    }

    @Before(value = "dynamicDataSourcePointCut(myDataSource)", argNames = "myDataSource")
    public void switchDataSource(MyDataSource myDataSource) {
        DynamicDataSourceSwitcher.setDataSource(myDataSource.value());
    }

    /**
     * 切点执行完后 切换成主数据库
     *
     * @param myDataSource
     */
    @After(value = "dynamicDataSourcePointCut(myDataSource)", argNames = "myDataSource")
    public void after(MyDataSource myDataSource) {
        DynamicDataSourceSwitcher.cleanDataSource();
    }
}
